package com.ruoyi.system.chaincode.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.system.chaincode.config.HyperLedgerFabricProperties;
import org.hyperledger.fabric.client.Contract;
import org.hyperledger.fabric.client.Gateway;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Service
public class ContractService {

    @Resource
    private Gateway gateway;

    @Resource
    private Contract contract;

    @Resource
    private HyperLedgerFabricProperties hyperLedgerFabricProperties;

    /**
     * 注册用户
     */
    public String registerUser(ChainAsset user) {
        if(null == user.getAssetKey()) return "Error: User ID cannot be empty";
        try {
            byte[] registerUsers = contract.submitTransaction("register", JSON.toJSONString(user));
            String s = new String(registerUsers, StandardCharsets.UTF_8);
            ChainData chainData = JSON.parseObject(new String(registerUsers, StandardCharsets.UTF_8), ChainData.class);

            if(chainData.getCode().equals("200")) {

                return s;
            } else {
                return "Error: " + chainData.getMsg();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }


    /**
     * 获取
     */
    public String getAsset(String assetKey, String txId) {
        String cxt = "getAsset";
        try {
            byte[] bytes = contract.evaluateTransaction(cxt, assetKey, txId);
            String s = new String(bytes, StandardCharsets.UTF_8);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 获取历史
     */
    public String getAsset(String assetKey) {
        String cxt = "getAsset";
        try {
            byte[] bytes = contract.evaluateTransaction(cxt, assetKey, "null");
            String s = new String(bytes, StandardCharsets.UTF_8);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

}
